package com.star.bookstore.member.controller;

import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;
import com.star.bookstore.member.entity.AdminEntity;
import com.star.bookstore.member.entity.UserEntity;
import com.star.bookstore.member.service.AdminService;
import com.star.bookstore.member.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@RefreshScope
@Controller
//@RequestMapping("/")
public class IndexController extends HttpServlet{

    @Autowired
    UserService userService;

    @Autowired
    AdminService adminService;

    //首页登录页
    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "/login";
    }


    //登录信息检查
    @PostMapping(value = {"/login/commit"})
    public String loginCheck(@RequestParam("username") String username,
                             @RequestParam("password") String password, Model model,
                             HttpServletRequest request, HttpServletResponse response){

        System.out.println("名字：" + username + "  " + "密码" + password);

        UserEntity userEntity = userService.loginCheck(username,password);
        if (userEntity == null){
            model.addAttribute("msg", "账号或者密码错误！(没有账号请先注册)");
            return "/login";
        }
        //获取随机登录码
        TimeBasedGenerator generator = Generators.timeBasedGenerator(EthernetAddress.fromInterface());
        String loginNumber = generator.generate().toString();
        //管理员登录
        if (userEntity.getUserId() == 0L){
            //获取uuid的随机码
            System.out.println(loginNumber);
            AdminEntity adminEntity = adminService.getById(1);
            adminEntity.setLoginNumber(loginNumber);
            adminService.updateById(adminEntity);
            try {
                response.sendRedirect("http://localhost:8081/#/?userId=0&loginNumber="+loginNumber);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //model.addAttribute("link","http://localhost:8081/#/?userId=0&loginNumber="+loginNumber);
            request.getSession().setAttribute("token","admin");
            return "/transfer_root";
        } else {
            //普通用户登录
            System.out.println(loginNumber);
            userEntity.setLoginNumber(loginNumber);
            userService.updateById(userEntity);
            try {
                response.sendRedirect("http://localhost:8082/#/?userId="+userEntity.getUserId()+"&loginNumber="+loginNumber);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //model.addAttribute("link","http://localhost:8082/#/?userId="+userEntity.getUserId()+"&loginNumber="+loginNumber);
            request.getSession().setAttribute("token",userEntity.getUserId());
            return "/transfer";
        }
    }

    //注册界面
    @GetMapping(value = {"/user/add","/login/user/add"})
    public String userAddPage(){

        return "user_add";
    }

    //拦截非法访问
    @RequestMapping("/member/login/intercept")
    public String interceptRequest(Model model){
        model.addAttribute("msg","请先登录以获取访问权限");
        return "/login";
    }

    //注册，若注册成功，插入数据，返回登录界面
    @PostMapping(value = {"/user/register"})
    public String userRegister(@RequestParam("username") String username,
                               @RequestParam("mobile") String mobile,
                               @RequestParam("password") String password,
                               @RequestParam("email") String email,Model model){
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        userEntity.setMobile(mobile);
        userEntity.setPassword(password);
        userEntity.setEmail(email);
        boolean flag = userService.checkRepeat(userEntity);
        if (flag) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userEntity.setCreateTime(simpleDateFormat.format(new Date()));
            userService.save(userEntity);
            model.addAttribute("msg", "用户注册成功");
            return "/login";
        }else{
            model.addAttribute("msg","用户名或手机号已存在");
            return "/user_add";
        }
    }

}
